﻿package  {
	
	import flash.utils.getDefinitionByName;
	import flash.display.MovieClip;
	import flash.utils.ByteArray;
	import com.serialization.json.JSON;
	
	public class Helper {
		
		
		
		public function Helper() {
			// constructor code
		}
		
		public static function moneyFormat(val:Number):String
		{
			//TODO: remove .00 if 00;
			return val.toFixed(2);
		}
		
		public static function getClass(name:String):Class
		{
			var ClassRef:Class;
			try
			{
				ClassRef = getDefinitionByName(name) as Class;
			} catch(e:Error)
			{
				trace("FATAL ERROR: В библиотеке отсутствует класс `"+name+"`.");
				ClassRef = null;
			}
			return ClassRef;
		}
		
		public static function createClass(name:String):*
		{
			var ClassRef:Class = Helper.getClass(name);
			return new ClassRef();
		}
		
		public static function rand(min:int, max:int, exclude:Array = null):int
		{
			var num:int = Math.floor((max-min+1)*Math.random())+min;
			if(exclude == null || exclude.length == 0)
				return num;
			while(exclude.indexOf(num) > -1)
			{
				num = Math.floor((max-min+1)*Math.random())+min;
			}
			return num;
		}
		
		public static function pack_data(_data:Object):ByteArray
		{
			var step:int = 4;
			var tmp:String = JSON.serialize(_data);
			var xor:int = Math.floor(Math.random()*255);
			var ret:ByteArray = new ByteArray();
			for(var i:int=0;i<tmp.length;i++)
			{
				ret.writeByte(tmp.charCodeAt(i) ^ xor);
				xor += step;
				if(xor>255)
					xor -= 256;
			}
			ret.writeByte(xor);
  			return ret;
		}
		
		public static function unpack_data(_data:ByteArray):Object
		{
			var ret:Object = null;
			var step:int = 4;
			try
			{
				var xor:int = _data[_data.length-1];
				for(var i:int=(_data.length-2);i>=0;i--)
				{
					xor -= step;
					if(xor<0)
						xor += 256;
					_data[i] = _data[i] ^ xor;
				}
				_data.length = _data.length -1;
				ret = JSON.deserialize(_data.toString());
				
			} catch(e:Error)
			{
				return null;
			}
			return ret;
		}

	}
	
}
